import traceback
from flask import current_app
import re

from app.services.ocr.utils.utils import convert_to_numbers


def analysis_doubao(topicsList):
    try:
        if not topicsList:
            return topicsList

        result = []

        for ret in topicsList:
            if not isinstance(ret, dict):
                current_app.logger.warning(f"跳过非字典对象: {ret} ({type(ret)})")
                continue

            an = ret.get('answer')
            if not an:
                continue

            an = an.strip().upper()

            # 处理 Y/N 判断题
            if 'Y' in an:
                ret['answer'] = '1'
                ret['optionA'] = 'Y:正确'
                ret['optionB'] = 'N:错误'
            elif 'N' in an:
                ret['answer'] = '1'
                ret['optionA'] = 'N:错误'
                ret['optionB'] = 'Y:正确'

            # 标准化答案数字并设置 noVerify
            ret['answer'] = convert_to_numbers(ret['answer'])
            ret['noVerify'] = True
            result.append(ret)

        return result

    except Exception as e:
        current_app.logger.error(f"❌ 解析豆包题目时出错: {e}")
        current_app.logger.error(traceback.format_exc())
        return []
